/*
 * Copyright 2007 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.gwt.homepage.smile.client.view;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.homepage.smile.client.presenter.EnneagramTestPresenter;
import com.google.gwt.i18n.client.Constants;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

import com.google.gwt.homepage.smile.client.presenter.EnneagramTestDoPresenter;
import com.google.gwt.homepage.smile.shared.EnneagramQuestionData;
import com.google.gwt.homepage.smile.shared.EnneagramQuestions;
import com.google.gwt.homepage.smile.shared.EnneagramTestResultBean;

/**
 * A Composite widget that abstracts a DynaTableWidget and a data provider tied
 * to the <@link SchoolCalendarService> RPC endpoint.
 */
public class EnneagramTestDoView extends Composite implements EnneagramTestDoPresenter.Display{

	//검사 결과를 저장할 배열(계산의 편의를 위해 크기를 +1함
	//int[][] testResult = new int[10][EnneagramQuestions.getQuestionNumForType()+1]; 
	
    //EnneagramQuestionData[] EnneagramQuestionOriginData = new EnneagramQuestionData[180];;
	
	EnneagramTestResultBean result  = new EnneagramTestResultBean();
  /**
   * A data provider that bridges the provides row level updates from the data
   * available through a <@link SchoolCalendarService>.
   */
  public class EnneagramProvider implements DynaTableDataProvider,ClickHandler{

    //private final SchoolCalendarServiceAsync calService;

    private int lastMaxRows = -1;

    //private Person[] lastPeople;

    
    
    private EnneagramQuestionData[] lastQuestion;
    
    private int lastStartRow = -1;

    public EnneagramProvider() {
    	
    	//결과테이블 초기화
    	//for(int i=0;i<10;i++){
    		//for(int j=0;j<EnneagramQuestions.getQuestionNumForType()+1;j++){
    			//testResult[i][j]=0;
    		//}
    	//}
    	
    	
    	
    	/*
    	for(int i=0;i<180;i++){
    		EnneagramQuestionData data =new EnneagramQuestionData(i,"calService = (SchoolCalendarServiceAsync) GWT.create(SchoolCalendarService.class);"+i,"1");
    		EnneagramQuestionOriginData[i]=data;
    	}
    	*/
      // Initialize the service.
      //
      //calService = (SchoolCalendarServiceAsync) GWT.create(SchoolCalendarService.class);

      // By default, we assume we'll make RPCs to a servlet, but see
      // updateRowData(). There is special support for canned RPC responses.
      // (Which is a totally demo hack, by the way :-)
      // 
      //ServiceDefTarget target = (ServiceDefTarget) calService;

      // Use a module-relative URLs to ensure that this client code can find
      // its way home, even when the URL changes (as might happen when you
      // deploy this as a webapp under an external servlet container).
      //String moduleRelativeURL = GWT.getModuleBaseURL() + "calendar";
      //target.setServiceEntryPoint(moduleRelativeURL);
    }

    public void updateRowData(final int startRow, final int maxRows,
        final RowDataAcceptor acceptor) {
      // Check the simple cache first.
      //
    	/*
      if (startRow == lastStartRow) {
        if (maxRows == lastMaxRows) {
          // Use the cached batch.
          //
          pushResults(acceptor, startRow, lastQuestion);
          return;
        }
      }
*/
      // Fetch the data remotely.
      //
      
      /*
      calService.getPeople(startRow, maxRows, new AsyncCallback<Person[]>() {
        public void onFailure(Throwable caught) {
          acceptor.failed(caught);
        }

        public void onSuccess(Person[] result) {
          lastStartRow = startRow;
          lastMaxRows = maxRows;
          lastPeople = result;
          pushResults(acceptor, startRow, result);
        }

      });*/
      
      
      
     // EnneagramQuestionData[] result=getEnneagramQeustionData(startRow, maxRows);
      EnneagramQuestions questionDao = new EnneagramQuestions();  
      EnneagramQuestionData[] result=questionDao.getQuestion(startRow, maxRows);
      boolean moreData = questionDao.moreData(startRow, maxRows);
      

    	  
      
      
      lastStartRow = startRow;
      lastMaxRows = maxRows;
      lastQuestion = result;
      pushResults(acceptor, startRow, result, moreData);

    }

    /*
    private EnneagramQuestionData[] getEnneagramQeustionData(int startRow, int maxRows){
    	
    	//Window.alert(Integer.toString(maxRows)+Integer.toString(startRow));
    	EnneagramQuestionData[] datas = new EnneagramQuestionData[maxRows];
    	for(int i=0, dataIndex=startRow; i< maxRows ;i++,dataIndex++){
    	  EnneagramQuestionData question = EnneagramQuestionOriginData[dataIndex];
    	  datas[i]=question;
    	}
    	return datas;
    }
    */
    private void pushResults(RowDataAcceptor acceptor, int startRow,
    		EnneagramQuestionData[] questionData, boolean moreData) {
      Widget[][] rows = new Widget[questionData.length][];
      for (int i = 0, n = rows.length; i < n; i++) {
    	EnneagramQuestionData question = questionData[i];
        rows[i] = new Widget[4];
        
        rows[i][0] = new HTML(question.getQuestion());
        
        RadioButton radioButton1 = new RadioButton(question.getType()+"_"+question.getQuesNum());
        radioButton1.setFormValue("3");//후에 constants에 넣자
        //if(testResult[Integer.parseInt(question.getType())][question.getQuesNum()]==3){
        if(result.isSelectedAgree(Integer.parseInt(question.getType()), question.getQuesNum())){
        	radioButton1.setValue(true);
        }
        radioButton1.addClickHandler(this);
        rows[i][1] = radioButton1;
        
        
        RadioButton radioButton2 = new RadioButton(question.getType()+"_"+question.getQuesNum());
        radioButton2.setFormValue("2");
        if(result.isSelectedMedi(Integer.parseInt(question.getType()), question.getQuesNum())){
        	radioButton2.setValue(true);
        }
        radioButton2.addClickHandler(this);
        rows[i][2] = radioButton2;
        
        RadioButton radioButton3 = new RadioButton(question.getType()+"_"+question.getQuesNum());
        radioButton3.setFormValue("1");
        if(result.isSelectedRej(Integer.parseInt(question.getType()), question.getQuesNum())){
        	radioButton3.setValue(true);
        }
        radioButton3.addClickHandler(this);
        rows[i][3] = radioButton3;
        
        /*
        HorizontalPanel vPanel = new HorizontalPanel();
        RadioButton radioButton1 = new RadioButton("question"+question.getQuesNum(),"agree");
        vPanel.add(radioButton1);
        RadioButton radioButton2 = new RadioButton("question"+question.getQuesNum(),"medeium");
        vPanel.add(radioButton2);
        RadioButton radioButton3 = new RadioButton("question"+question.getQuesNum(),"reject");
        vPanel.add(radioButton3);
        rows[i][1] = vPanel;
        */
      }
      acceptor.accept(startRow, rows, moreData);
    }
    
    public void onClick(ClickEvent event) {
	    // note that in general, events can have sources that are not Widgets.
    	RadioButton sender = (RadioButton) event.getSource();
    	//라디오버튼을 readonly로
    	//sender.setEnabled(false);
    	
    	//데이터 저장
    	String clickedName = sender.getName();
    	//Window.alert(clickedName);
    	int clickedAnswer = Integer.parseInt(sender.getFormValue());
    	
    	String[] type_answerNum = clickedName.split("_");
    	
    	//데이터 저장
    	result.saveResult(Integer.parseInt(type_answerNum[0]),Integer.parseInt(type_answerNum[1]),clickedAnswer);
    	//testResult[Integer.parseInt(type_answerNum[0])][Integer.parseInt(type_answerNum[1])]=clickedAnswer;
    	
    }
  }
  
  
  
  private final EnneagramProvider calProvider = new EnneagramProvider();

  private final DynaTableWidget dynaTable;

  //결과확인 버튼
  private final Button resultBtn; 
  
  public EnneagramTestDoView(int visibleRows) {
	
	 
	  
    String[] columns = new String[] {"질 문", "동의","보통","반대"};
    String[] styles = new String[] {"question", "answer", "answer", "answer"};
    dynaTable = new DynaTableWidget(calProvider, columns, styles, visibleRows);
    initWidget(dynaTable);
    
    //결과보기 버튼 생성
    resultBtn = new Button("결과확인"); 
    
   
    System.out.println("결과확인");
    //dynaTable 아래쪽에 넣기
    dynaTable.setSouthWidget(resultBtn);
  }
  
  //경고창 보여줌
  public void showDialog(){
	 
  		DialogBox dialogBox =  createDialogBox();
		dialogBox.setAnimationEnabled(true);
		dialogBox.setGlassEnabled(true);
		dialogBox.center();
        dialogBox.show();
  }  
  
  
  
  /**
   * Create the dialog box for this example.
   *
   * @return the new dialog box
   */
  private DialogBox createDialogBox() {
    // Create a dialog box and set the caption text
    final DialogBox dialogBox = new DialogBox();
    //dialogBox.ensureDebugId("cwDialogBox");
    dialogBox.setText("확인");
   
    dialogBox.setPixelSize(300, 70);
    
    // Create a table to layout the content
    VerticalPanel dialogContents = new VerticalPanel();
    dialogContents.setSpacing(4);
    dialogBox.setWidget(dialogContents);

    // Add some text to the top of the dialog
    HTML details = new HTML("답변하지 않은 문항이 있습니다!");
    dialogContents.add(details);
    dialogContents.setCellHorizontalAlignment(
        details, HasHorizontalAlignment.ALIGN_CENTER);

    
    
    
   
 
    
    
    // Add a close button at the bottom of the dialog
    Button closeButton = new Button(
        "닫기", new ClickHandler() {
          public void onClick(ClickEvent event) {
            dialogBox.hide();
          }
        });
    dialogContents.add(closeButton);
    
    if (LocaleInfo.getCurrentLocale().isRTL()) {
      dialogContents.setCellHorizontalAlignment(
          closeButton, HasHorizontalAlignment.ALIGN_LEFT);

    } else {
      dialogContents.setCellHorizontalAlignment(
          closeButton, HasHorizontalAlignment.ALIGN_RIGHT);
    }
	
    // Return the dialog box
    return dialogBox;
  }
  

  @Override
  protected void onLoad() {
    dynaTable.refresh();
  }

  

  public HasClickHandlers getResultButton(){
	  return resultBtn;
  }
  
  //HasClickHandlers getDeleteButton();
  //HasClickHandlers getList();
  //void setData(List<String> data);
  
  public boolean getAllChecked(){
	  return result.getAllChecked();
  }
  
  private EnneagramTestResultBean getResult(){
	  return result;
  }
  
  
//결과창 보여줌
  public void showTestResult(){
	  EnneagramTestResultBean result=getResult();
	  System.out.println("#############");
  		DialogBox dialogBox =  createDialogBox(result);
  		//System.out.println("333");
		dialogBox.setAnimationEnabled(true);
		dialogBox.setGlassEnabled(true);
		dialogBox.center();
        dialogBox.show();
  }  
  
  
  
  /**
   * 테스트 결과를 보여준다.
   *
   * @return the new dialog box
   */
  private DialogBox createDialogBox(EnneagramTestResultBean result) {
	  
	  //차트를 만들기 위한 데이터
	  System.out.println("11111111111111");
	  int valueArray[]=result.getResultValue();
	  System.out.println("222222222222222");
	  int maxValue=result.getQuestionNumForType();
	  System.out.println("33333333333333333");
	  //String encodedData = simpleEncode(valueArray, maxValue);
	  String myType=result.getMyType();
	  System.out.println("4444444444444444444");
	  String myTypeName=result.getTypeName(myType);
	  System.out.println("555555555555555555");
	  String myWing=result.getMyWing();
	  System.out.println("6666666666666666666666");
	  String myWingName=result.getTypeName(myWing);	
	  System.out.println("777777777777777777777");
	  for(int k=0 ; k<9;k++){
		  System.out.println("###########"+valueArray[k]);
	  }

    
    final DialogBox dialogBox = new DialogBox();
    //dialogBox.ensureDebugId("cwDialogBox");
    
    
    
    
    dialogBox.setText("검사 결과");
   
    //dialogBox.setPixelSize(250, 70);
    
    // Create a table to layout the content
    VerticalPanel dialogContents = new VerticalPanel();
    dialogContents.setSpacing(5);
    dialogBox.setWidget(dialogContents);

    
    ////////////////////////////////////////////
    /*
    Grid grid = new Grid(result.getQuestionNumForType()+1, 10);
    for(int i=1;i<=9;i++){
    	 grid.setWidget(0, i, new HTML(i+"유형"));
    }
    
    for(int i=1;i<=result.getQuestionNumForType();i++){
   	 grid.setWidget(i, 0, new HTML(Integer.toString(i)+"번"));
   }
   
    
    for(int i=1;i<=result.getQuestionNumForType();i++){
    	for(int j=1;j<=9;j++){
    		String resultTxt="";
    		if(result.isSelectedAgree(j,i)){
    			resultTxt="동의";
    		}else if(result.isSelectedMedi(j,i)){
    			resultTxt="보통";
    		}else if(result.isSelectedRej(j,i)){
    			resultTxt="반대";
    		}
    		grid.setWidget(i, j, new HTML(resultTxt));
    	}
    }
    dialogContents.add(grid);
    dialogContents.setCellHorizontalAlignment(
    		grid, HasHorizontalAlignment.ALIGN_CENTER);
   */
  ////////////////////////////////////////////////////////////
   
    
    //차트
    //chxt : 기준이 되는 행, 열 
    //chxr : index, 최소값, 최대값, step
    //chxl : index, label
    HTML chart = new HTML("<img src='http://chart.apis.google.com/chart?chxt=x,y&amp;chxr=1,0,100,20&amp;chxl=0:|1유형|2유형|3유형|4유형|5유형|6유형|7유형|8유형|9유형&amp;chbh=a,5,20&amp;chs=500x250&amp;cht=bvg&amp;chco=76A4FB&amp;chd=t:"+valueArray[0]+","+valueArray[1]+","+valueArray[2]+","+valueArray[3]+","+valueArray[4]+","+valueArray[5]+","+valueArray[6]+","+valueArray[7]+","+valueArray[8]+"' />");
    dialogContents.add(chart);
    
    
    
    ////////////////////////////////
    HTML strType = new HTML("당신의 "+myType+"유형("+myTypeName+"), 날개는 "+myWing+"유형("+myWingName+")입니다.");
    dialogContents.add(strType);
    ////////////////////////////////
    
    
    
    Hyperlink link = new Hyperlink("나의 유형 정보 보러가기","enneagram_features");
    //link.setStyleName("link");
    link.addStyleName("goEnneResultLink");
    dialogBox.hide();
    dialogContents.add(link);
    
    /////////////////////////////////
    /*
    Button goDetail = new Button(
        "나의 유형 정보 보러가기", new ClickHandler() {
          public void onClick(ClickEvent event) {
        	  dialogBox.hide();
        	  History.newItem("list");
          }
        });
    dialogContents.add(goDetail);
    */
    ////////////////////////////////////
    
    
    
    //System.out.println("555");
    // Add a close button at the bottom of the dialog
    Button closeButton = new Button(
        "닫기", new ClickHandler() {
          public void onClick(ClickEvent event) {
            dialogBox.hide();
          }
        });
    dialogContents.add(closeButton);
    
    if (LocaleInfo.getCurrentLocale().isRTL()) {
      dialogContents.setCellHorizontalAlignment(
          closeButton, HasHorizontalAlignment.ALIGN_LEFT);

    } else {
      dialogContents.setCellHorizontalAlignment(
          closeButton, HasHorizontalAlignment.ALIGN_RIGHT);
    }
	
    // Return the dialog box
    return dialogBox;
  }
  
  
  //simple Encoding
  private native String simpleEncode(int[] valueArray, int maxValue)
  /*-{
  	return $wnd.simpleEncode(valueArray, maxValue);
  }-*/;
  
  
  
  public Widget asWidget() {
	    return this;
  }
  
  
}
